<template>
  <div class="search-wrap">
    <input
      type="text"
      :placeholder="placeholder"
      :maxlength="maxlength"
      :value="inputValue"
      @input="searchData($event)"
    />
  </div>
</template>
              
              
<script>
import { ref, computed, watch } from "vue";
import { useStore } from "vuex";
import getData from "@/services";
import { getNowDate, formatUserDate } from "@/libs/utils";

export default {
  name: "SearchInput",
  props: {
    placeholder: String,
    maxlength: Number,
  },

  setup(props) {
    const inputValue = ref(""),
      store = useStore(),
      state = store.state;
    const searchData = (e) => {
      inputValue.value = e.target.value;
      const field = computed(() => state.field).value;
      if (inputValue.value.length === props.maxlength) {
        //输入框输入的值（日期）与模块的输入长度匹配
        getData(store, field, formatUserDate(inputValue.value));
      } else if (inputValue.value === 0) {
        //清空搜索框
        getData(store, field, getNowDate(field));
      }
    };
    watch(
      () => {
        return state.field;
      },
      () => {
        //监听field的变化，如果field发生改变，说明切换了路由，清空搜索框的值
        inputValue.value = "";
      }
    );

    return {
      inputValue,
      searchData,
    };
  },
};
</script>
              
              
<style lang="scss" scoped>
.search-wrap {
  position: fixed;
  top: 0.44rem;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 0.38rem;
  padding: 0.03rem 0.1rem;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  background-color: #fff;

  input {
    width: 100%;
    height: 100%;
    font-size: 0.14rem;
    border: 1px solid #ddd;
    text-indent: 0.1rem;
    border-radius: 0.03rem;

    &:focus {
      border-color: #ed4040;
      box-shadow: 0 0 0.02rem #ed4040;
      transition: all 0.3s;
    }
  }
}
</style>